import { NextRequest, NextResponse } from 'next/server';
import { getDb } from '@/lib/db';

export async function GET() {
  try {
    const db = await getDb();
    const list = await db.listCollections();
    return NextResponse.json({
      type: (process.env.DB_TYPE as string) || 'sqlite',
      collections: list.data || [],
      success: true
    });
  } catch (e: any) {
    return NextResponse.json({ success: false, error: e?.message || 'DB error' }, { status: 500 });
  }
}

export async function POST(request: NextRequest) {
  try {
    const body = await request.json();
    const { action, collection, data, filter, options } = body || {};
    const db = await getDb();

    switch (action) {
      case 'create':
        return NextResponse.json(await db.create(collection, data));
      case 'createMany':
        return NextResponse.json(await db.createMany(collection, data));
      case 'findOne':
        return NextResponse.json(await db.findOne(collection, filter));
      case 'findMany':
        return NextResponse.json(await db.findMany(collection, filter, options));
      case 'update':
        return NextResponse.json(await db.update(collection, filter, data));
      case 'updateMany':
        return NextResponse.json(await db.updateMany(collection, filter, data));
      case 'delete':
        return NextResponse.json(await db.delete(collection, filter));
      case 'deleteMany':
        return NextResponse.json(await db.deleteMany(collection, filter));
      case 'count':
        return NextResponse.json(await db.count(collection, filter));
      case 'createIndex':
        return NextResponse.json(await db.createIndex(collection, data));
      case 'dropCollection':
        return NextResponse.json(await db.dropCollection(collection));
      case 'listCollections':
        return NextResponse.json(await db.listCollections());
      default:
        return NextResponse.json({ success: false, error: 'Unknown action' }, { status: 400 });
    }
  } catch (e: any) {
    return NextResponse.json({ success: false, error: e?.message || 'DB error' }, { status: 500 });
  }
}